<template>
  <div class="app-container">
    <div class="flex-box">
      <div class="inline-box">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="项目" required>
            <el-select
                v-model="form.belong_project"
                :disabled="operation_type !== 0 ? true:false"
                filterable
                placeholder="前置用例所属项目"
                @change="projectChange">
              <el-option
                v-for="item in data_options.project_list"
                :key="item.id"
                :label="item.project_name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="模块">
            <el-select v-model="data_options.module" filterable placeholder="前置用例所属模块" @change="moduleChange">
              <el-option
                v-for="item in data_options.module_list"
                :key="item.id"
                :label="item.module_name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="选择用例">
            <el-table
              :data="data_options.case_list"
              v-loading="data_options.case_list_Loading"
              element-loading-text="Loading"
              border
              fit
              :row-class-name="tableRowClassName"
              @row-click="rowClick">
              <el-table-column
                prop="id"
                label="用例ID"
                min-width="20%"
                show-overflow-tooltip>
              </el-table-column>
              <el-table-column
                prop="name"
                label="用例名称"
                sortable
                min-width="80%"
                show-overflow-tooltip>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="data_options.case_list_pagination.total"
            :current-page="data_options.case_list_pagination.page_num"
            @current-change="handleCurrentChange">
          </el-pagination>
        </el-form>
      </div>
      <span>
        <i class="el-icon-d-arrow-right"></i>
      </span>
      <div class="inline-box">
        <el-row :gutter="20">
          <el-col :span="13">
            <el-input v-model="form.suite_name">
              <template slot="prepend">套件名称</template>
            </el-input>
          </el-col>
          <el-col :span="5">
            <el-button type="success" @click="onSubmit">保存</el-button>
          </el-col>
          <el-col :span="5">
            <el-button @click="onCancel">取消</el-button>
          </el-col>
        </el-row>
        <br>
        <label>套件用例列表:</label>
        <br><br>
        <tableList
          ref="TableList"
          :columns-text="suite_case_column"
          v-if="getinfo_flag || !operation_type"
          :list_data.sync="form.suite_case_list"
          @changeList="changeLists"
          @changeItemStatus="changeListItemStatus"
        />
      </div>
    </div>
  </div>
</template>

<script>
import tableList from '@/components/tableList'
import { getProjectSumList } from '@/api/project/table'
import { getModuleSumList } from '@/api/module/table'
import { getCaseList } from '@/api/test_case/table'
import { getSuite, createSuite, updateSuite } from '@/api/test_suite/table'

export default {
  components: {
    tableList
  },
  data() {
    return {
      operation_type: 0, // 0:create 1:update 2:copy
      suiteID: '',
      getinfo_flag: false,
      ispagination: false,
      form: {
        suite_name: '',
        belong_project: '',
        suite_case_list: [],
        author: ''
      },
      suite_case_column: [
        {
          label: '用例ID',
          prop: 'id',
          minWidth: '15%',
          valueKey: 'id'
        },
        {
          label: '用例名称',
          prop: 'name',
          minWidth: '70%',
          valueKey: 'name'
        },
        {
          label: '状态',
          prop: 'status',
          minWidth: '15%',
          valueKey: 'status'
        },
      ],
      data_options: {
        module: '',
        project_list: [],
        module_list: [],
        case_list: [], // [{ 'id': '1', 'name': 'test_测试所属用例1_名称字段' }]
        case_list_pagination: {
          total: 0,
          page_current: 1,
          page_num: 1,
          page_size: 10
        },
        case_list_Loading: false,
      }
    }
  },
  created() {
    this.operation_type = this.$route.query.operation_type || 0
    this.suiteID = this.$route.query.id || ''
    console.log('Opertaion Type: ' + this.operation_type)
    console.log('suiteID: ' + this.suiteID)

    if (this.operation_type !== 0) {
      this.getData() //编辑或复制
      // this.projectChange()
    } else {
      this.fetchProjectSumList() //新增
    }
  },
  methods: {
    onSubmit() {
      if (this.operation_type.toString() === '1') {
        updateSuite(this.form).then(response => {
          if (response.status === '000000') return
          this.$message.success('更新成功')
          this.$router.replace(`/test_suite/suite_list`)
        })
      } else {
        createSuite(this.form).then(response => {
          if (response.status === '000000') return
          this.$message.success('创建成功')
          this.$router.replace(`/test_suite/suite_list`)
        })
      }
    },
    onCancel() {
      this.$confirm('此操作将退出编辑, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.replace(`/test_suite/suite_list`)
        this.$message({
          type: 'success',
          message: '退出成功!',
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退出'
        })
      })
    },
    getSuiteData() {
      var params = {}
      params['id'] = this.suiteID
      return new Promise((resolve, reject) => {
        getSuite(params).then(response => {
          this.form = response.data
          // this.form.suite_name = response.data.suite_name
          this.form.suite_case_list = response.data.include
          // this.form.belong_project = response.data.belong_project
          this.getinfo_flag = response.success
          resolve(response);
        }).catch(e =>{
          reject(e)
        })
      })
    },
    async getData() {
      await this.getSuiteData(),
      await this.fetchProjectSumList(),
      await this.fetchModuleSumList()
    },
    fetchProjectSumList() {
      return new Promise((resolve, reject) => {
        getProjectSumList().then(response => {
          this.data_options.project_list = response.results
          console.log(response.results)
          resolve(response);
        }).catch(e =>{
          reject(e)
        })
      });
    },
    fetchModuleSumList() {
      var params = { 'belong_project': this.form.belong_project }
      return new Promise((resolve, reject) => {
        getModuleSumList(params).then((response) => {
          this.data_options.module_list = response.results
          console.log(response.results)
          resolve(response);
        }).catch(e =>{
          reject(e)
        })
      });
    },
    projectChange() {
      // http请求
      console.log('project' + this.form.belong_project)
      this.data_options.module = ''
      this.data_options.case_list = ''
      this.form.suite_case_list = []

      var params = { 'belong_project': this.form.belong_project }
      return new Promise((resolve, reject) => {
        getModuleSumList(params).then((response) => {
          this.data_options.module_list = response.results
          resolve(response)
        }).catch(e =>{
          reject(e)
        })
      })
    },
    moduleChange() {
      // http请求
      console.log('module' + this.data_options.module)
      this.data_options.case_list = []

      this.fetchCaseList()
    },
    fetchCaseList: function() {
      if (this.form.belong_project && this.data_options.module) {
        var params = {
          'belong_project': this.form.belong_project,
          'belong_module': this.data_options.module,
          'ordering': '-update_time'
        }
      console.log(this.ispagination)
      if (this.ispagination){
        params['page_num'] = this.data_options.case_list_pagination.page_num
      }else{
        params['page_num'] = 1
      }
        this.data_options.case_list_Loading = true

        return new Promise((resolve, reject) => {
          getCaseList(params).then(response => {
            this.data_options.case_list = response.results
            this.data_options.case_list_pagination.total = response.count
            this.data_options.case_list_Loading = false
          }).then((data) =>{
            this.optionalCaseListChange()
          }).catch(e =>{
            reject(e)
          })
          if (this.ispagination == false){
            this.data_options.case_list_pagination.page_num = 1
           }
            this.ispagination = false
        })
      }
    },
    handleCurrentChange: function(val) { //可选用例列表翻页
      this.ispagination = true
      this.data_options.case_list_pagination.page_num = val
      this.fetchCaseList()
    },
    optionalCaseListChange: function() { //可选用例列表变更
      if (this.form.suite_case_list.length) {
        for (var i = 0; i < this.data_options.case_list.length; i++){
          var item = this.data_options.case_list[i]
          for (var j =0; j < this.form.suite_case_list.length; j++) {
            if (this.data_options.case_list[i].id === this.form.suite_case_list[j].id) {
              this.$set(this.data_options.case_list[i], 'class_name', 'selected')
            }
          }
        }
      }
    },
    rowClick: function(row) {
      var item = this.data_options.case_list.filter(item => item.id === row.id)[0]
      console.log("选中项如下：")
      console.log(item)
      if (item) {
        var counter = 0
        for (var i = 0; i < this.form.suite_case_list.length; i++) {
          if (item.id === this.form.suite_case_list[i].id) {
            counter++
          }
        }
        if (counter >= 1) {
          this.$message({
            message: '提示：[' + item.name + '] , 在预置用例列表中已存在！',
            type: 'info'
          })
        } else {
          item.status = true  // 在suite_case_list中，默认是状态是true
          this.form.suite_case_list.push(JSON.parse(JSON.stringify(item)))
          this.$set(row, 'class_name', 'selected')
        }
      }
    },
    changeLists: function(obj) {
      this.form.suite_case_list = obj.list

      if (obj.item) {
        for (var i = 0; i < this.data_options.case_list.length; i++) {
          if (this.data_options.case_list[i].id === obj.item.id) {
            this.$set(this.data_options.case_list[i], 'class_name', '')
          }
        }
      }
    },
    changeListItemStatus: function(obj) {
      this.$set(this.form.suite_case_list[obj.index], 'status', obj.statusValue)
    },
    tableRowClassName: function({ row, rowIndex }) {
      console.log(row.class_name)
      if (row.class_name !== 'selected') {
        return ''
      } else {
        return 'success-row'
      }
    },
    changeChildList() {
      this.$eventBus.$emit("changeChildList", )
    }
  }
}
</script>

<style lang="scss">
.el-table .success-row {
  background: #f0f9eb;
}

.line {
  text-align: center;
}

.flex-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-content: center;

  .inline-box {
    display: inline-block;
    width: 500px;

    &:last-child {
      width: 600px;
    }
  }

  > span {
    font-size: 20px;
    line-height: 300px;
  }
}

</style>

